package com.sy.core.website;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sy.core.model.SyOrderInfo;
import com.sy.core.model.SyOrderInfoDetail;
import com.sy.core.model.SyReceiverMessage;
import com.sy.core.model.SysUser;
import com.sy.core.service.OrderInfoDetailService;
import com.sy.core.util.MD5Util;
import com.sy.core.util.RestResult;
import com.sy.core.util.SysConst;
import com.sy.core.web.BaseCtl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.Index;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 我的订单，个人资料模块
 */
@Controller
@RequestMapping("website/personalData")
public class PersonalDataCtl extends BaseCtl {
    protected  static String prefix = "/website/";

    /**
     * 个人资料页面
     * @param mm
     * @return
     */
    @RequestMapping("me_data")
    public String index(ModelMap mm){
        mm.addAttribute("user",getLoginUser());
        return prefix+ "me_data";
    }

    /**
     * 修改个人资料页面
     */
    @RequestMapping("me_data_modify")
    public String me_data_modify(ModelMap mm){
        mm.addAttribute("user",getLoginUser());
        return prefix+"me_data_modify";
    }

    /**
     * 修改个人密码页面
     */
    @RequestMapping("me_data_password")
    public String me_data_password(ModelMap mm){
        mm.addAttribute("user",getLoginUser());
        return prefix+"me_data_password";
    }

    /**
     * 修改个人资料
     */
    @RequestMapping("updatePersonaInfo")
    @ResponseBody
    public RestResult updatePersonaInfo(SysUser sysUser){
        RestResult rr = null;
        try {
            if(!sysUser.getEmail().matches(SysConst.MAIL)) return new RestResult("500","邮箱格式不正确");
            if(sysUser.getName().length()>50) return new RestResult("500","用户名称过长");
            sysUserService.update(sysUser);
            rr = new RestResult("200","修改成功");
        } catch (Exception e) {
            logger.error("修改个人资料失败");
            rr = new RestResult("500","修改个人资料失败");
            logger.error(e.toString());
        }
        return rr;
    }

    /**
     * 修改密码
     */
    @RequestMapping("updatePassword")
    @ResponseBody
    public RestResult updatePassword(String oldPass,String newPass1,String newPass2,SysUser sysUser){
        RestResult rr =null;
        if(StringUtils.isNotBlank(oldPass)&&(MD5Util.generate(oldPass, getLoginUser().getSalt())).equals(getLoginUser().getPassword())){
            if(StringUtils.isNotBlank(newPass1)&&newPass1.equals(newPass2)){
                if(!newPass1.matches(SysConst.PASSWORD)) return new RestResult("500","密码强度不够");
                sysUser.setPassword(MD5Util.generate(newPass1, getLoginUser().getSalt()));
                sysUser.setPk(getLoginUser().getPk());
                try {
                    sysUserService.update(sysUser);
                    rr=new RestResult("200","修改密码成功");
                } catch (Exception e) {
                    rr=new RestResult("500","修改密码失败");
                    logger.error("修改密码失败");
                }
            }else{
                rr=new RestResult("500","新密码不一致");
            }
        }else{
            rr=new RestResult("500","原始密码错误");
        }
        return rr;
    }

    /**
     * 地址列表页面
     */
    @RequestMapping("me_address_list")
    public String me_address_list(ModelMap mm, SyReceiverMessage syReceiverMessage){
        SysUser sysUser = getLoginUser();
        mm.addAttribute("user",sysUser);
        syReceiverMessage.setReceiverPk(sysUser.getPk());
        List<Map<String, Object>> addressList = addressService.queryList(syReceiverMessage);
        String path=prefix+"me_address_no";
        if(addressList!=null&&addressList.size()>0){
            mm.addAttribute("addressList",addressList);
            path=prefix+"me_address_list";
        }
        return path;
    }

    /**
     * 新增或修改地址页面
     */
    @RequestMapping("me_address_add")
    public String me_address_add(ModelMap mm,String pk){
        mm.addAttribute("user",getLoginUser());
        if(pk!=null){
            Map<String, Object> address = addressService.queryOne(pk);
            mm.addAttribute("address",address);
            mm.addAttribute("pk",pk);
        }
        return prefix+"me_address_add";
    }

    /**
     * 保存编辑或新增的地址
     */
    @RequestMapping("addressAddAndEdit")
    @ResponseBody
    public RestResult addressAddAndEdit(SyReceiverMessage syReceiverMessage){
        RestResult rr = null;
        if(syReceiverMessage.getReceiverProvince().equals("请选择")||syReceiverMessage.getReceiverCounty().equals("请选择")||syReceiverMessage.getReceiverCity().equals("请选择")){
            return new RestResult("300","省市区不能为空");
        }
        if(!StringUtils.isNotBlank(syReceiverMessage.getReceiverAddress())||syReceiverMessage.getReceiverAddress().length()>200){
            return new RestResult("300","地址详情必填且不能超过200个字");
        }
        if(!syReceiverMessage.getReceiverName().matches(SysConst.USERNAME)){
            return new RestResult("300","姓名必填且不超过25个字符");
        }
        if(!syReceiverMessage.getReceiverPhone().matches(SysConst.PHONE)){
            return new RestResult("300","手机号为空或格式不正确");
        }
        try {
            addressService.addressAddAndEdit(syReceiverMessage);
            rr = new RestResult("200","操作成功");
        } catch (Exception e) {
            rr = new RestResult("500","操作失败");
            logger.error("操作失败");
        }
        return rr;
    }

    /**
     * 删除地址
     */
    @RequestMapping("addressDel")
    @ResponseBody
    public RestResult addressDel(String pk){
        RestResult rr = null;
        try {
            addressService.delete(pk);
            rr = new RestResult("200","删除成功");
        } catch (Exception e) {
            logger.error(e.toString());
            rr = new RestResult("500","删除失败");
        }
        return rr;
    }

    /**
     * 个人订单列表页面
     * @return
     */
    @RequestMapping("me_order_list")
    public String me_order_list(ModelMap mm, SyOrderInfo syOrderInfo, SyOrderInfoDetail syOrderInfoDetail,
                                Integer page,Integer limit){
        mm.addAttribute("user",getLoginUser());
        syOrderInfo.setOrderPersion(getLoginUser().getPk());
        List lists = new ArrayList();//定义一个list来放置多个订单子表list
        PageHelper.startPage(page,limit);
        List<Map<String, Object>> orderList = orderService.queryList(syOrderInfo);
        PageInfo<Map<String,Object>> info = new PageInfo<>(orderList);
        for (int i = 0; i <orderList.size() ; i++) {
            syOrderInfoDetail.setOrderPk((String)orderList.get(i).get("pk"));
            List<Map<String, Object>> orderdetailList = orderInfoDetailService.queryList(syOrderInfoDetail);
            lists.add(orderdetailList);
        }
        mm.addAttribute("orderList",info);
        mm.addAttribute("lists",lists);
        mm.addAttribute("orderStatus",syOrderInfo.getOrderStatus());
        mm.addAttribute("currentPage",page);
        return prefix+"me_order_list";
    }

    /**
     * 个人订单页面删除功能
     */
    @RequestMapping("orderDel")
    @ResponseBody
    public RestResult orderDel(String pk){
        RestResult rr = null;
        try {
            orderService.delete(pk);
            rr = new RestResult("200","删除成功");
        } catch (Exception e) {
            rr = new RestResult("500","删除失败");
            logger.error("删除失败");
        }
        return rr;
    }
}
